using DocumentCreationSystem.Services;
using DocumentCreationSystem.Views;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace DocumentCreationSystem
{
    /// <summary>
    /// AI助手工具调用功能测试
    /// </summary>
    public class TestAgentToolCalls
    {
        public static async Task Main(string[] args)
        {
            Console.WriteLine("=== AI助手工具调用功能测试 ===\n");

            // 创建服务容器
            var host = Host.CreateDefaultBuilder(args)
                .ConfigureServices((context, services) =>
                {
                    // 注册基本服务
                    services.AddSingleton<IDataStorageService, JsonDataStorageService>();
                    services.AddScoped<IProjectService, ProjectService>();
                    services.AddScoped<IDocumentService, DocumentService>();
                    services.AddSingleton<IThinkingChainService, ThinkingChainService>();
                    services.AddSingleton<IAIService>(provider =>
                        new AIServiceManager(
                            provider.GetRequiredService<IConfiguration>(),
                            provider.GetRequiredService<ILogger<AIServiceManager>>(),
                            provider.GetRequiredService<IThinkingChainService>(),
                            provider));
                    services.AddScoped<IProjectToolsService, ProjectToolsService>();
                    services.AddScoped<IAIToolsService, AIToolsService>();
                    services.AddScoped<AgentToolService>();
                    services.AddHttpClient();
                })
                .Build();

            var serviceProvider = host.Services;

            try
            {
                // 测试基础工具调用解析
                await TestBasicToolCallParsing();

                // 测试高级工具调用解析
                await TestAdvancedToolCallParsing();

                // 测试工具执行
                await TestToolExecution(serviceProvider);

                // 测试系统提示词生成
                await TestSystemPromptGeneration(serviceProvider);

                Console.WriteLine("\n=== 所有测试完成 ===");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"测试失败: {ex.Message}");
                Console.WriteLine($"详细错误: {ex}");
            }
        }

        private static async Task TestBasicToolCallParsing()
        {
            Console.WriteLine("1. 测试基础工具调用解析");

            var testText = @"
请帮我查看项目文件。[TOOL:list_files].[/TOOL]
然后读取配置文件：[TOOL:read_file]config.json[/TOOL]
最后分析内容：[TOOL:analyze_story]这是一个测试故事内容[/TOOL]
";

            // 模拟AgentChatDialog的工具调用解析
            var toolCalls = ExtractToolCallsForTest(testText);

            Console.WriteLine($"发现 {toolCalls.Count} 个基础工具调用:");
            foreach (var call in toolCalls)
            {
                Console.WriteLine($"  - 工具: {call.ToolName}, 参数: '{call.Parameters}', 类型: {call.ToolType}");
            }
            Console.WriteLine();
        }

        private static async Task TestAdvancedToolCallParsing()
        {
            Console.WriteLine("2. 测试高级工具调用解析");

            var testText = @"
我需要搜索代码库：[AITOOL:search-codebase]{""query"":""AI服务"",""maxResults"":10}[/AITOOL]
然后进行网络搜索：[AITOOL:web-search]{""query"":""C# WPF教程"",""language"":""zh-CN""}[/AITOOL]
";

            var toolCalls = ExtractToolCallsForTest(testText);

            Console.WriteLine($"发现 {toolCalls.Count} 个高级工具调用:");
            foreach (var call in toolCalls)
            {
                Console.WriteLine($"  - 工具: {call.ToolName}, 参数: '{call.Parameters}', 类型: {call.ToolType}");
            }
            Console.WriteLine();
        }

        private static async Task TestToolExecution(IServiceProvider serviceProvider)
        {
            Console.WriteLine("3. 测试工具执行");

            var aiToolsService = serviceProvider.GetRequiredService<IAIToolsService>();
            var agentToolService = serviceProvider.GetRequiredService<AgentToolService>();

            // 测试基础工具
            Console.WriteLine("测试基础工具 - list_files:");
            try
            {
                var result = await agentToolService.ExecuteToolAsync("list_files", ".", CancellationToken.None);
                Console.WriteLine($"  结果: {result.Substring(0, Math.Min(100, result.Length))}...");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"  错误: {ex.Message}");
            }

            // 测试高级工具
            Console.WriteLine("测试高级工具 - search-codebase:");
            try
            {
                var parameters = new Dictionary<string, object>
                {
                    ["query"] = "AI服务",
                    ["maxResults"] = 5
                };
                var result = await aiToolsService.ExecuteToolAsync("search-codebase", parameters);
                Console.WriteLine($"  成功: {result.IsSuccess}, 消息: {result.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"  错误: {ex.Message}");
            }
            Console.WriteLine();
        }

        private static async Task TestSystemPromptGeneration(IServiceProvider serviceProvider)
        {
            Console.WriteLine("4. 测试系统提示词生成");

            var aiToolsService = serviceProvider.GetRequiredService<IAIToolsService>();

            try
            {
                var availableTools = await aiToolsService.GetAvailableToolsAsync();
                Console.WriteLine($"可用工具数量: {availableTools.Count}");

                var categories = availableTools.GroupBy(t => t.Category).ToDictionary(g => g.Key, g => g.Count());
                Console.WriteLine("工具分类统计:");
                foreach (var category in categories)
                {
                    Console.WriteLine($"  {category.Key}: {category.Value} 个工具");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"  错误: {ex.Message}");
            }
            Console.WriteLine();
        }

        // 模拟AgentChatDialog中的工具调用解析逻辑
        private static List<TestToolCall> ExtractToolCallsForTest(string text)
        {
            var toolCalls = new List<TestToolCall>();

            // 提取基础工具调用
            ExtractBasicToolCallsForTest(text, toolCalls);

            // 提取高级工具调用
            ExtractAdvancedToolCallsForTest(text, toolCalls);

            return toolCalls;
        }

        private static void ExtractBasicToolCallsForTest(string text, List<TestToolCall> toolCalls)
        {
            var startIndex = 0;

            while (true)
            {
                var toolStart = text.IndexOf("[TOOL:", startIndex);
                if (toolStart == -1) break;

                var toolEnd = text.IndexOf("[/TOOL]", toolStart);
                if (toolEnd == -1) break;

                var toolText = text.Substring(toolStart, toolEnd - toolStart + 7);
                var toolContent = text.Substring(toolStart + 6, toolEnd - toolStart - 6);

                var colonIndex = toolContent.IndexOf(']');
                if (colonIndex > 0)
                {
                    var toolName = toolContent.Substring(0, colonIndex);
                    var parameters = toolContent.Substring(colonIndex + 1);

                    toolCalls.Add(new TestToolCall
                    {
                        ToolName = toolName,
                        Parameters = parameters,
                        OriginalText = toolText,
                        ToolType = TestToolType.Basic
                    });
                }

                startIndex = toolEnd + 7;
            }
        }

        private static void ExtractAdvancedToolCallsForTest(string text, List<TestToolCall> toolCalls)
        {
            var startIndex = 0;

            while (true)
            {
                var toolStart = text.IndexOf("[AITOOL:", startIndex);
                if (toolStart == -1) break;

                var toolEnd = text.IndexOf("[/AITOOL]", toolStart);
                if (toolEnd == -1) break;

                var toolText = text.Substring(toolStart, toolEnd - toolStart + 9);
                var toolContent = text.Substring(toolStart + 8, toolEnd - toolStart - 8);

                var colonIndex = toolContent.IndexOf(']');
                if (colonIndex > 0)
                {
                    var toolName = toolContent.Substring(0, colonIndex);
                    var parameters = toolContent.Substring(colonIndex + 1);

                    toolCalls.Add(new TestToolCall
                    {
                        ToolName = toolName,
                        Parameters = parameters,
                        OriginalText = toolText,
                        ToolType = TestToolType.Advanced
                    });
                }

                startIndex = toolEnd + 9;
            }
        }

        private class TestToolCall
        {
            public string ToolName { get; set; } = string.Empty;
            public string Parameters { get; set; } = string.Empty;
            public string OriginalText { get; set; } = string.Empty;
            public TestToolType ToolType { get; set; } = TestToolType.Basic;
        }

        private enum TestToolType
        {
            Basic,
            Advanced
        }
    }
}
